


'''
    k个一组反转链表
'''



# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        '''
            思路：
            可以先k个k个这样反转，即问题是我先反转k个，然后用k个反转前的节点（即反转后处于尾部的节点）去链接下一个k个的反转的节点
            然后再对k个节点里面的元素进行反转
        '''

        if not head:
            return None
        a = b = head
        for i in range(k):
            if not b:
                return head
            b= b.next
        newhead = self.reverse(head,a,b)
        a.next = self.reverseKGroup(b,k)
        return newhead
        
        #反转链表里的元素
            
    ###  反转链表
    def reverse(self,head,a,b):
        t = None
        p = q = head
        while p != b:
            q = p.next
            p.next = t
            t= p 
            p = q
        return t
            
        

